<template>
  <div class="login-card">
    <i class="fas fa-tv login-home-icon" @click="$router.push('/')"></i>
    <div class="col-span-2 p-6 pb-2">
      <form class="mt-10" @submit.prevent="onSubmit">
        <login-input name="name" type="text" placeholder="请输入登录账号" />
        <login-input name="password" type="password" placeholder="请输入登录密码" />
        <login-input name="code" type="text" placeholder="请输入验证码">
          <template v-slot:end>
            <button v-if="countDown === NUM_SECONDS" class="ml-2 login-btn" type="button" @click="getCode">
              获取验证码
            </button>
            <span v-else class="code-img">
              <div v-html="codeUrl" @click="getCode"></div>
              <span>{{ countDown }}S</span>
            </span>
          </template>
        </login-input>
        <button class="mt-3 login-btn" type="submit">登录</button>
      </form>
      <slot name="footer"></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import userApi from '@/apis/user';
import useAuth from '@/hooks/useAuth';
import { veeValidate, yup } from '@/plugins/validate';

// 登录
const { login } = useAuth();

// 验证码
const codeUrl = ref();

// 倒计时
const NUM_SECONDS = 60;
const countDown = ref(NUM_SECONDS);
const timer = ref();

// 倒计时函数
const countDownFn = () => {
  if (countDown.value > 0) {
    countDown.value--;
    timer.value = setTimeout(() => {
      countDownFn();
    }, 1000);
  } else {
    clearTimeout(timer.value);
    countDown.value = NUM_SECONDS;
  }
};

// 自定义校验
const rules = {
  name: yup.string().required().label('账号'),
  password: yup.string().required().min(6).label('登录密码'),
  code: yup.string().required().length(4).label('验证码'),
};

const { handleSubmit } = veeValidate.useForm({
  initialValues: {
    name: '',
    password: '',
    code: '',
  },
  validationSchema: rules,
});

const onSubmit = handleSubmit((values) => {
  login(values);
});

// 获取验证码
const getCode = async () => {
  countDownFn();
  codeUrl.value = await userApi.getCode();
};
</script>

<style scoped lang="scss">
.login-card {
  @apply w-[360px] bg-[url('/images/login.png')] relative bg-cover rounded-md shadow-md overflow-hidden;
  .login-home-icon {
    @apply absolute top-3 right-3 text-[#35a4aeed] cursor-pointer;
  }
}

.login-btn {
  @apply bg-[#35a4aeed] text-white rounded-sm py-1 w-full hover:bg-[#77c9d0c2] duration-300 whitespace-nowrap;
  &:disabled {
    background-color: #77c9d0c2;
    cursor: not-allowed;
  }
}

.code-img {
  @apply flex items-center relative;
  div {
    @apply h-full ml-1 bg-[#35a4aeed] rounded-sm;
  }
  span {
    mix-blend-mode: difference;
    @apply absolute left-[-2rem] flex items-center h-full text-[#b0e7ed];
  }
}
</style>
